package com.marisfrolg.storage;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;
import com.marisfrolg.base.BaseApplication;
import com.marisfrolg.entity.Check;
import com.marisfrolg.entity.Model;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.util.ReadCodeController;
import com.marisfrolg.util.StringUtil;
import com.marisfrolg.util.WebServicesUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;

public class CheckActivity extends ItemActivity {
	@ViewInject(R.id.checklist)
	private ListView checklist;
	private AlertDialog addcheckAlert;
	private ReadCodeController rcc;
	@ViewInject(R.id.addCheck)
	private BootstrapButton addCheck;
	@ViewInject(R.id.footbuttons)
	private View footbuttons;
	private boolean isChooseMode=false;
	private Set<Integer> checkids=new HashSet<Integer>();
	private ProgressDialog updateProgress;
	private WebServicesUtil ws;
	private WSHandler handler;
	private StringBuffer faultItems=new StringBuffer();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_check);
		rcc=((BaseApplication)getApplication()).getReadCodeController();
		rcc.setHandler(sHandler);
		rcc.Open();
		ViewUtils.inject(this);
		sHandler=new ScanHandler(this);
		handler=new WSHandler(this);
		ws=new WebServicesUtil(this,handler);
		refresh();
		//addCheck.performClick();
	}
	@OnItemClick(R.id.checklist)
	public void chooseCheck(AdapterView<?> a, View v, int arg2, long arg3) {
		if(isChooseMode){
			CheckBox c=(CheckBox)v.findViewById(R.id.checkBox);
			TextView idtv=(TextView)v.findViewById(R.id.check_id);
			int id=Integer.valueOf(idtv.getText()+"");
			if(checkids.contains(id)){
				checkids.remove(id);
			}else{
				checkids.add(id);
			}
			c.toggle();
		}else{
			TextView checkId=(TextView)v.findViewById(R.id.check_id);
			TextView checknum=(TextView)v.findViewById(R.id.check_code);
			Intent in=new Intent();
			try {
				in.putExtra("checkid", Integer.valueOf(checkId.getText()+""));
				in.putExtra("checknum", checknum.getText()+"");
			} catch (Exception e) {
				e.printStackTrace();
			}
			in.setClass(this, CheckItemActivity.class);
			startActivity(in);
		}
	}
	@OnClick(R.id.addCheck)
	public void addCheck(View v){
		if(isChooseMode){
			new AlertDialog.Builder(this).setPositiveButton("确定", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					submit(true);
				}
			}).setNegativeButton("取消", null).setTitle("注意").setMessage("确定提交全部选项吗?").show();
		}else{
			final EditText name=new EditText(this);
			LayoutParams lp=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
			name.setLayoutParams(lp);
			addcheckAlert=new AlertDialog.Builder(this).setTitle("输入仓位:").setView(name).setPositiveButton("确定", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(StringUtil.isEmpty(name.getText().toString())){
						new AlertDialog.Builder(CheckActivity.this).setTitle("提示").setMessage("不可为空").setPositiveButton("确定",null).show();
						return;
					}
					try {
						Check dbc=db.findFirst(Selector.from(Check.class).where(WhereBuilder.b("code", "=", name.getText()+"")));
						if(dbc!=null){
							new AlertDialog.Builder(CheckActivity.this).setPositiveButton("确定",null).setTitle("提示").setMessage("已存在").show();
							return;
						}
						Check c=new Check();
						c.setCode((name.getText()+"").trim().toUpperCase(new Locale("US")));
						c.date=new Date(System.currentTimeMillis());
						db.saveBindingId(c);
					} catch (DbException e) {
						e.printStackTrace();
					}
					refresh();
				}
			}).setNegativeButton("取消", null).create();
			addcheckAlert.setOnKeyListener(new OnKeyListener() {
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					if(event.getAction()==KeyEvent.ACTION_DOWN&&(keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10|| keyCode == KeyEvent.KEYCODE_F11||keyCode == KeyEvent.KEYCODE_BACK)){
						rcc.scan_start();
					}else if(event.getAction()==KeyEvent.ACTION_UP&&(keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10|| keyCode == KeyEvent.KEYCODE_F11)){
						rcc.scan_stop();
					}
					return false;
				}
			});
			addcheckAlert.show();
		}
	}
	@OnClick(R.id.checkicon)
	public void showChoice(View v){
		int visible=View.GONE;
		String buttonvalue="添加";
		if(isChooseMode){
			isChooseMode=false;
			footbuttons.setVisibility(visible);
		}else{
			isChooseMode=true;
			visible=View.VISIBLE;
			buttonvalue="全部提交";
			footbuttons.setVisibility(visible);
		}
		int amount=checklist.getChildCount();
		for(int i=0;i<amount;i++){
			checklist.getChildAt(i).findViewById(R.id.checkBox).setVisibility(visible);
		}
		addCheck.setText(buttonvalue);
	}
	@OnClick(R.id.batSubmit)
	public void batSubmit(View v){
		if(checkids.size()==0){
			return;
		}
		new AlertDialog.Builder(this).setPositiveButton("确定", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				submit(false);
			}
		}).setNegativeButton("取消", null).setTitle("注意").setMessage("确定提交所选项吗?").show();
	}
	private void submit(boolean isAll){
		if(isAll){
			for(int i=0;i<checklist.getAdapter().getCount();i++){
				TextView tvid=(TextView)checklist.getAdapter().getView(i, null, checklist).findViewById(R.id.check_id);
				int id=Integer.valueOf(tvid.getText()+"");
				checkids.add(id);
			}
		}
		if(checkids.size()==0){
			new AlertDialog.Builder(CheckActivity.this).setTitle("提示").setMessage("无数据").setPositiveButton("确定",null).show();
			return;
		}
		updateProgress=new ProgressDialog(this);
		updateProgress.setTitle("正在提交");
		updateProgress.setCancelable(true);
		updateProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		updateProgress.setMax(checkids.size());
		updateProgress.show();
//		Timer timer=new Timer(true);
//		int delay=300;
		List<Map<String,Object>> paramsList=new ArrayList<Map<String,Object>>();
		for(Integer id:checkids){
			try {
				Check c=db.findFirst(Selector.from(Check.class).where(WhereBuilder.b("id", "=", id)));
				List<Model>ms=db.findAll(Selector.from(Model.class).where(WhereBuilder.b("checkid", "=", id)));
				final HashMap<String , Object> params=new HashMap<String, Object>();
				params.put("BIN", c.getCode());
				Gson gson=new Gson();
				Type type = new TypeToken<User>() {}.getType();
				params.put("USER", gson.toJson(loginUser, type));
				params.put("BINID", c.getId());
				params.put("ITEMS", StringUtil.getModelXml(ms));
				paramsList.add(params);
//				TimerTask updateTT=new TimerTask() {
//					public void run() {
//						ws.call(WebServicesUtil.ACTION_UpdateBinActual2, params, WebServicesUtil.URL_ACTION_UpdateBinActual2, WebServicesUtil.METHOD_ACTION_UpdateBinActual2);
//					}
//				};
//				delay+=50;
//				timer.schedule(updateTT, delay);
//				ws.call(WebServicesUtil.ACTION_UpdateBinActual2, params, WebServicesUtil.URL_ACTION_UpdateBinActual2, WebServicesUtil.METHOD_ACTION_UpdateBinActual2);
//				try {
//					Thread.sleep(50);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
			} catch (DbException e) {
				e.printStackTrace();
			}
		}
		ws.callArray(WebServicesUtil.ACTION_UpdateBinActual2, paramsList, WebServicesUtil.URL_ACTION_UpdateBinActual2, WebServicesUtil.METHOD_ACTION_UpdateBinActual2);
	}
	//@OnClick(R.id.batDel)
	public void batDel(View v){
		new AlertDialog.Builder(this).setPositiveButton("确定", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(checkids.size()!=0){
					for(Integer id:checkids){
						try {
							db.deleteById(Check.class, id);
							List<Model>ms=db.findAll(Selector.from(Model.class).where(WhereBuilder.b("checkid", "=", id)));
							db.deleteAll(ms);
						} catch (DbException e) {
							e.printStackTrace();
						}
					}
					refresh();
				}else{
					new AlertDialog.Builder(CheckActivity.this).setTitle("提示").setMessage("没有数据").setPositiveButton("确定",null).show();
					return;
				}
			}
		}).setNegativeButton("取消", null).setTitle("注意").setMessage("确定删除所选项吗?").show();
	}
	@OnClick(R.id.allChoose)
	public void allChoose(View v){
		int amount=checklist.getAdapter().getCount();
		if(amount==checkids.size()){
			checkids.clear();
			amount =checklist.getChildCount();
			for(int i=0;i<amount;i++){
				((CheckBox)checklist.getChildAt(i).findViewById(R.id.checkBox)).setChecked(false);
			}
		}else{
			for(int i=0;i<amount;i++){
				TextView tvid=(TextView)checklist.getAdapter().getView(i, null, checklist).findViewById(R.id.check_id);
				int id=Integer.valueOf(tvid.getText()+"");
				checkids.add(id);
			}
			amount =checklist.getChildCount();
			for(int i=0;i<amount;i++){
				((CheckBox)checklist.getChildAt(i).findViewById(R.id.checkBox)).setChecked(true);
			}
		}
	}
	
	private void refresh(){
		try {
			checkids.clear();
			List<Check> checks=db.findAll(Selector.from(Check.class).orderBy("date", true));
			List<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
			if(checks==null){
				checklist.setAdapter(null);
				return;
			}
			for (Check c : checks) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("code", c.getCode());// 图像资源的ID
				SimpleDateFormat fmt=new SimpleDateFormat("MM/dd/yy",Locale.US);//日期转换
				SimpleDateFormat fmt2=new SimpleDateFormat("MM/dd HH:mm",Locale.US);//日期转换
				map.put("date", fmt.format(c.date));
				if(c.getUpdate()!=null){
					map.put("update", "提交时间:"+fmt2.format(c.getUpdate()));
				}else{
					map.put("update", "未提交");
				}
				map.put("checkId", c.getId()+"");
				listItem.add(map);
			}
			SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,// 数据源
					R.layout.checks_item,// ListItem的XML实现
					// 动态数组与ImageItem对应的子项
					new String[] { "code", "date","checkId","update"},
					// ImageItem的XML文件里面的一个ImageView,两个TextView ID
					new int[] { R.id.check_code, R.id.check_date,R.id.check_id,R.id.update}){//覆盖getView根据是否在选择状态生成view
				public View getView(int position, View convertView,
						ViewGroup parent) {
					View v=super.getView(position, convertView, parent);
					CheckBox checkBox=(CheckBox)v.findViewById(R.id.checkBox);
					TextView idtv=(TextView)v.findViewById(R.id.check_id);
					int id=Integer.valueOf(idtv.getText()+"");
					checkBox.setChecked(checkids.contains(id));
					if(isChooseMode){
						checkBox.setVisibility(View.VISIBLE);
					}else{
						checkBox.setVisibility(View.GONE);
					}
					return v;
				}
			};
			checklist.setAdapter(listItemAdapter);
//			for(int i=0;i<listItemAdapter.getCount();i++){
//				View v=listItemAdapter.getView(i, null, null);
//				CheckBox checkBox=(CheckBox)v.findViewById(R.id.checkBox);
//				if(isChooseMode){
//					checkBox.setVisibility(View.VISIBLE);
//				}else{
//					checkBox.setVisibility(View.GONE);
//				}
//			}
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		refresh();
	}
	private static class ScanHandler extends Handler {
		WeakReference<CheckActivity> wactivity;

		ScanHandler(CheckActivity activity) {
			wactivity = new WeakReference<CheckActivity>(activity);
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ReadCodeController.CODEREAD: {
				CheckActivity activity = wactivity.get();
				String old = msg.obj + "";
				Intent in=new Intent();
				if(!StringUtil.isBin(old)){
					activity.play_sound(false);
					Toast.makeText(activity, "扫入的不是仓位号", Toast.LENGTH_SHORT).show();
					return;
				}
				//View v=activity.getCurrentFocus();
				if(activity.addcheckAlert!=null){
					View e =activity.addcheckAlert.getCurrentFocus();
					if (e instanceof EditText){
						EditText et=(EditText)e;
						et.setText(old);
						activity.addcheckAlert.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
						activity.addcheckAlert=null;
					}
				}/**else if (v instanceof EditText){
					EditText et=(EditText)v;
					et.setText(old);
				}**/
				else{
					try {
						Check dbc=activity.db.findFirst(Selector.from(Check.class).where(WhereBuilder.b("code", "=", old+"")));
						if(dbc!=null){
							activity.play_sound(false);
							new AlertDialog.Builder(activity).setPositiveButton("确定",null).setTitle("提示").setMessage("已存在").show();
							return;
						}
						Check c=new Check();
						c.setCode((old+"").trim().toUpperCase(new Locale("US")));
						c.date=new Date(System.currentTimeMillis());
						activity.db.saveBindingId(c);
						in.putExtra("checkid", c.getId());
						in.putExtra("checknum", c.getCode());
					} catch (DbException e) {
						e.printStackTrace();
					}
					activity.refresh();
				}
				activity.play_sound(true);
				//进入盘数
				in.setClass(activity, CheckItemActivity.class);
				activity.startActivity(in);
				
				break;
			}
			default:
				break;
			}
		}
	};
	private static class WSHandler extends Handler {
		WeakReference<CheckActivity> wactivity;
		WSHandler(CheckActivity activity) {
			wactivity = new WeakReference<CheckActivity>(activity);
		}

		public void handleMessage(Message msg) {
			CheckActivity activity = wactivity.get();
			switch (msg.what) {
			case WebServicesUtil.ACTION_UpdateBinActual2:{
				String result=msg.obj+"";
				if("0".equals(result)){
					Check c=null;
					try {
						c=activity.db.findFirst(Selector.from(Check.class).where(WhereBuilder.b("id", "=", msg.arg1)));
						if(c!=null){
							c.setUpdate(new Date(System.currentTimeMillis()));
							activity.db.update(c);
						}
					} catch (DbException e) {
						e.printStackTrace();
					}
				}else if("1".equals(result)){
					Check c=null;
					try {
						c=activity.db.findFirst(Selector.from(Check.class).where(WhereBuilder.b("id", "=", msg.arg1)));
					} catch (DbException e) {
						e.printStackTrace();
					}
					activity.faultItems.append("\n"+c.getCode());
				}
				activity.updateProgress.setProgress(activity.updateProgress.getProgress()+1);
				if(activity.updateProgress.getMax()==activity.updateProgress.getProgress()){
					if(activity.updateProgress.isShowing()){
						activity.updateProgress.dismiss();
						new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("    提交完成"+(activity.faultItems.length()!=0?"\n失败项目:":"")+activity.faultItems).show();
						activity.faultItems=new StringBuffer();
						activity.refresh();
					}
				}
				break;
			}
			case WebServicesUtil.TIMEOUT:{
				new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("连接超时").show();
				break;
			}
			case WebServicesUtil.NETUNREACHABLE:{
				Toast.makeText(activity, "网络无法连接或连接已取消,请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		}
	};
	@Override
	public void onBackPressed() {
		if(progressDialog!=null&&progressDialog.isShowing()){
			progressDialog.dismiss();
		}else{
			finish();
		}
		super.onBackPressed();
	}
}


